from flask import Flask
from flask import make_response, render_template,request,jsonify,send_file
from mask_rcnn.mask_rcnn import MASK_RCNN
import os
from keras import models
from PIL import Image
from datetime import datetime
import base64
import cv2
import json
import numpy as np
from flask_cors import *
from mask_rcnn.utils import visualize
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)
CORS(app, supports_credentials=True)
# 这个权重没有保存模型结构，无法load使用
# my_model=models.load_model('D:\\PythonInPackage\\flaskProject\\model\\epoch100_loss0.158_val_loss2.646.h5')


@app.route('/')
def hello_word():
    return make_response(render_template('Card.html'))

@app.route('/test')
def Test():
    return render_template('Card.html')

def return_img_stream(img_path):
    img_stream=''
    with open(img_path,'rb') as img_f:
        img_stream=img_f.read()
        img_stream=base64.b64encode(img_stream).decode()
    return img_stream

def base64_cv2(base64_str):
    imgString = base64.b64decode(base64_str)
    nparr = np.fromstring(imgString,np.uint8)
    image = cv2.imdecode(nparr,cv2.IMREAD_COLOR)
    return image


@app.route('/perdictImg',methods=['GET','POST'])
def perdict():
    mask_rcnn = MASK_RCNN()
    print(request.files)
    if 'file' in request.files:
        # 获取并保存到本地
        print(request.files['file'])
        objFile = request.files.get('file')
        strFileName = objFile.filename
        strFilePath = "./static/myImages/" + strFileName
        objFile.save(strFilePath)
        nowtime = datetime.now().strftime("%Y-%m-%d, %H:%M:%S")
        # db.session.add(Image(name=strFileName,imgTime=nowtime,imgData=objFile))
        # db.session.commit()
        # 2022/5/12 更新了scipy
        # 正在预测....
        print('Predicting...')
        perdict_image = mask_rcnn.detect_image(cv2.imread(strFilePath))
        # 预测结果保存到本地
        strPerdictPath = "./static/myImages/" + "perdict_" + strFileName
        perdict_image.save(strPerdictPath)

        # 保存每一个mask
        mask_save_path="./static/myImages/mask/"
        perdictImgList = []
        perdictImgList.append(return_img_stream(strPerdictPath))
        N=100
        i=0
        visualize.set_cnt()
        while i<N:
            mask,x=mask_rcnn.mask_every_image(perdict_image)
            N=x
            i+=1
            path=mask_save_path+str(i)+'.jpg'
            mask.save(path)
            perdictImgList.append(return_img_stream(path))
        # 这个地方打开了可能会出现问题
        mask_rcnn.close_session()
        res={'perdictImgList': perdictImgList}
        print(type(res))

        return jsonify(res)
    else:
        err = "erro"
        return err
    pass

# 进行轮廓相似度的比对
def get_compare(compareImgPath):
    # 获取对比图片的轮廓
    compareImg=cv2.imread(compareImgPath,0)
    _, contours, hierarchy = cv2.findContours(compareImg, cv2.RETR_TREE, 1)
    print(type(contours))
    contours.sort(key=lambda c: cv2.contourArea(c), reverse=True)
    cnt=contours[0]
    return cnt

# 导入正确的json 文件
def get_json_file():
    Path='./static/Data/宅基地数据.json'
    with open(Path, 'r', encoding='utf8') as fp:
        json_data = json.load(fp)
    return  json_data

@app.route('/upJsonFile',methods=['GET','POST'])
def get_json():
    # 获取上传的json 文件
    if 'file' in request.files:
        # 保存上传的json文件
        objFile = request.files.get('file')
        strFileName = objFile.filename
        strFilePath = "./static/myFiles/" + strFileName
        objFile.save(strFilePath)
        res=back_json(strFilePath);
        return jsonify(res)
    else:
        return "WithoutFileErro"
    # 然后本地保存,数据库
    pass

def back_json(path):
    # 返回json让，前端画出宅基地的框
    with open(path, 'r', encoding='utf8') as fp:
        json_data = json.load(fp)
    return  json_data

def get_cur(lng,lat):
    # 在json 文件中查找需要的点,或许给个文件id会更好，然后从数据库中查找文件
    points = [
        [
            2326,
            6394
        ],
        [
            2376,
            6259
        ],
        [
            2410,
            6269
        ],
        [
            2361,
            6404
        ],
        [
            2326,
            6394
        ]
    ]

    draw_points = np.array([points], np.int32)
    return draw_points

@app.route('/Compare',methods=['GET','POST'])
def Compare():
    # 使用hu矩进行比对即可
    # 获取用户选择的图片
    res=request.get_json()
    print(res)
    index=res['index']
    lnglat=res['lnglat']
    print(index,lnglat)
    comparePath='./static/myImages/mask/'+str(index)+'.jpg'
    cnt1=get_cur(lnglat[0],lnglat[1])
    cnt2=get_compare(comparePath)

    ret = cv2.matchShapes(cnt1, cnt2, 1, 0.0)
    return jsonify({'Same':ret})


if __name__ == '__main__':
     app.run(host='0.0.0.0', port='5000')
